package handler;

import DataBase.myDB;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimerHandler {
    private Calendar calendar;
    private Timer timer;
    private TimerTask task;

    public TimerHandler(){
        calendar=Calendar.getInstance();
        timer=new Timer();
    }

    public void HandlingLongTermTrade(){
        calendar.set(Calendar.HOUR_OF_DAY, 12);//控制小时
        calendar.set(Calendar.MINUTE, 0);//控制分钟，
        calendar.set(Calendar.SECOND, 0);//控制秒，
        task=new TimerTask() {
            @Override
            public void run() {
                myDB database=new myDB("banksystem");
                String sql="select * from sub_account natural join trade_type where not duration = 'instant' ";
                try {
                    ResultSet resultSet=database.getStatement().executeQuery(sql);
                    while(resultSet.next()){
                        long type=resultSet.getLong("type_ID");
                        Timestamp tradeDate=resultSet.getTimestamp("trade_date");
                        Timestamp current=new Timestamp(System.currentTimeMillis());
                        long duration=Long.parseLong(resultSet.getString ("duration"));
                        if((type==4&&current.getDay()==tradeDate.getDay()&&current.getMonth()==tradeDate.getMonth()&&current.getYear()-tradeDate.getYear()<=duration)||(current.getDay()==tradeDate.getDay()&&current.getYear()-tradeDate.getYear()<=duration)){
                            double money=resultSet.getDouble("money");
                            double rate=resultSet.getDouble("rate");
                            long account_ID=resultSet.getLong("account_ID");
                            myDB innerDB=new myDB("banksystem");
                            String innersql="insert into trade_record (money,trade_date,teller_ID,account_ID,type_ID) values ("+money*rate+",'"+new Timestamp(System.currentTimeMillis())+"',3,"+account_ID+",6)";
                            innerDB.getStatement().execute(innersql);
                        }
                    }
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        };
        timer.schedule(task,60*60*1000*12,60*60*1000*24);
    }
}
